using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using System.Text;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Debug = UnityEngine.Debug;
using QFramework;


public class MqttclinetModel :AbstractModel
    {

        public  IMqttClient mqttClient { get; set; }
    protected override void OnInit()
    {
        Debug.Log("");
    }
       public async void CreatClient(string ClinetID, string IP, int port, string[] Topic)
        {
           
            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithClientId(ClinetID) 
                .WithTcpServer(IP, port) 
                .WithCleanSession()
                .Build();

   
            mqttClient = new MqttFactory().CreateMqttClient();

     
            mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
            {      
                foreach (var mqtt in Topic)
                {
                    mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(mqtt).Build()).Wait();
                }

            });


            mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(e =>
            {
                // this.SendEvent(new MqttServerFSM());
                Debug.Log(e.ConnectResult);
            });

 
            mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);

                this.SendEvent(new MqttTopic(){ topicmsg = e.ApplicationMessage.Topic,code = message});});

      
            await mqttClient.ConnectAsync(mqttClientOptions);
        }



      public  async void SendMessage(string topic, string message)
        {

            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(message)
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                .Build();


            await mqttClient.PublishAsync(mqttMessage);
        }


    }
